// getCrombs(): Retrieve crombs located at the current position - Returns array of object Crombs
// getCrombsCount(): Retrieve crombs count at the current postion without loading content - Returns integer
// getCrombsClosest(): Retreives the distance to the closest cromb beyond current position - Returns distance in meters

//Object
function Cromb() {
    this.author = null;
    this.message = null;
    this.datetime = null;
    this.distance = null;
    this.orientation = 0;
    this.likeCounter = 0;
    this.longitude=0;
    this.latitude=0;
    this.id = 0;
}
function Crime(){
    this.description;
    this.counter;
    this.crimeID;
}
var EventType = new Array(0);
function Event(){
    this.id = null;
    this.typeId = null;
    this.description = null;
    this.name = null;
    this.creationDate=null;
    this.endingDate=null;
    this.distance=null;
    this.longitude = null;
    this.latitude = null;
    this.bearing = null;
}
function User() {
    this.username = null;
    this.email = null;
    this.totalPost = 0;
}
var crombUser = null;
function News() {
    this.message = null;
    this.datetime = null;
}
function Tag() {
    this.tag = null;
    this.distance = null;
    this.orientation = 0;
}
function ClosestCromb() {
    this.distance = 0;
    this.orientation = 0;
}
var lastCrombs = undefined;
// auto update Crombs List
setInterval(getCrombs,30000);
getCrombs();

function getEventList()
{
    if (!isGPSEnabled()) {
        return;
    }
    var events = new Array(0);
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action=events";
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("event");
        events = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var event = new Event();
            event.id = nodes[i].getAttribute("id");
            event.typeId = nodes[i].getAttribute("typeid");
            event.description = nodes[i].getAttribute("description");
            event.name = nodes[i].getAttribute("name");
            event.longitude = nodes[i].getAttribute("longitude");
            event.latitude = nodes[i].getAttribute("latitude");
            event.distance = renderDistance(nodes[i].getAttribute("distance"));
            event.bearing = nodes[i].getAttribute("bearing");
            event.creationDate = renderDate(nodes[i].getAttribute("creationdate"));
            event.endingDate = renderDate(nodes[i].getAttribute("endingdate"));
            events[i] = event;
        }
        var nodes = xml.getElementsByTagName("eventtype");
        EventTypes = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var event = new Event();
            event.typeId = nodes[i].getAttribute("typeid");
            event.description = nodes[i].getAttribute("description");
            EventTypes[i] = event;
        }
    }
    return events;
}
function getCrimeList(global)
{
    if (!isGPSEnabled()) {
        return;
    }
    var crimes = new Array(0);
    var type = "localcrimelist";
    if (global===true){
        type="globalcrimelist";
    }
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action="+type;
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("crime");
        crimes = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var description = nodes[i].getAttribute("description");
            var counter = nodes[i].getAttribute("counter");
            var crimeid = nodes[i].getAttribute("crimeid");
            var crime = new Crime();
            crime.description = description;
            crime.counter = counter;
            crime.crimeID = crimeid;
            crimes[i] = crime;
        }
    }
    return crimes;
}
function getCrombs()
{
    if (!isGPSEnabled()) {
        return;
    }
    var crombs = new Array(0);
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action=crombs";
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("cromb");
        crombs = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var author = nodes[i].getAttribute("author");
            var datetime = nodes[i].getAttribute("datetime");
            var message = nodes[i].childNodes[0].nodeValue;
            var dist = nodes[i].getAttribute("distance");
            var orientation = nodes[i].getAttribute("orientation");
            var likeCounter = nodes[i].getAttribute("likecounter");
            var id = nodes[i].getAttribute("id");
            var cromb = new Cromb();
            cromb.author = author;
            cromb.datetime = renderDatetime(datetime);
            cromb.message = replaceURLWithHTMLLinks(message);
            cromb.distance = dist;
            cromb.orientation = orientation;
            cromb.likeCounter = likeCounter;
            cromb.id = id;
            cromb.longitude = nodes[i].getAttribute("lon");
            cromb.latitude = nodes[i].getAttribute("lat");
            crombs[i] = cromb;
        }
    }
    lastCrombs = crombs;
    return crombs;
}
function updateCrombLikeCounter(crombId) {
    var url = "servlets/DataManager?action=like&crombid=" + escape(crombId);
    var xml = getXML(url);
}
function reportCrime(crimeId) {
    var url = "servlets/DataManager?action=reportcrime&crimeid=" + escape(crimeId)+"&lon=" + gpsLongitude + "&lat=" + gpsLatitude;
    var xml = getXML(url);
}
function postEvent(eventId, eventName,eventDuration) {
    var url = "servlets/DataManager?action=postevent&eventid=" + escape(eventId)+"&lon=" + gpsLongitude + "&lat=" + gpsLatitude+"&eventname=" + escape(eventName) + "&eventduration=" + escape(eventDuration);
    var xml = getXML(url);
}
function getTopCrombers() {
    var url = "servlets/DataManager?action=topcrombers";
    var xml = getXML(url);

    var users = new Array(0);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("user");
        users = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var username = nodes[i].getAttribute("username");
            var totalpost = nodes[i].getAttribute("totalpost");
            var user = new User();
            user.username=username;
            user.totalPost=totalpost;
            users[i] = user;
        }
    }
    return users;
}
function getTags(userTag)
{
    if (!isGPSEnabled()) {
        return;
    }
    if (userTag === undefined) {
        userTag = "";
    }
    var tags = new Array(0);
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action=tags&tag=" + escape(userTag);
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("hashtag");
        tags = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var name = nodes[i].getAttribute("name");
            var dist = nodes[i].getAttribute("distance");
            var orientation = nodes[i].getAttribute("orientation");
            var tag = new Tag();
            tag.tag = name;
            tag.distance = dist;
            tag.orientation = orientation;
            tags[i] = tag;
        }
    }
    return tags;
}
function getCrombsCount()
{
    if (!isGPSEnabled()) {
        return;
    }
    var count = 0;
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action=scan";
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("count");
        //There should be only one...
        for (var i = 0; i < nodes.length; i++) {
            count = nodes[i].getAttribute("value");
        }
    }
    return count;
}
function getCrombsClosest()
{
    if (!isGPSEnabled()) {
        return undefined;
    }
    var closest = new ClosestCromb();
    var url = "servlets/DataManager?lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&action=distance";
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("distance");
        //There should be only one...
        for (var i = 0; i < nodes.length; i++) {
            closest.distance = nodes[i].getAttribute("value");
            closest.orientation = nodes[i].getAttribute("orientation");
        }
    }
    return closest;
}
function getNews()
{
    var url = "servlets/DataManager?action=news";
    var newsList = new Array(0);
    var xml = getXML(url);
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("news");
        newsList = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var datetime = nodes[i].getAttribute("datetime");
            var message = nodes[i].childNodes[0].nodeValue;
            var news = new News();
            news.datetime = renderDatetime(datetime);
            news.message = replaceURLWithHTMLLinks(message);
            newsList[i] = news;
        }
    }
    return newsList;
}
function logout() {
    var url = "servlets/DataManager?action=logout";
    var xml = getXML(url);
    crombUser = null;
}
var createLoginMessage = "";
function createlogin(username, useremail) {
    var url = "servlets/DataManager?action=createlogin&useremail=" + escape(useremail) + "&username=" + escape(username);
    var xml = getXML(url);
    var status = false;
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("status");
        for (var i = 0; i < nodes.length; i++) {
            var content = nodes[i].childNodes[0].nodeValue;
            crombUser = null;
            createLoginMessage = content;
            if (content === "SUCCESS") {
                status = true;
                break;
            }
        }
    }
    return status;
}
// auto login

function initAutoLogin(){
    var user = getCookie("lastemail");
    var pass = getCookie("lastpassword");
    if (user !== null && pass !== null){
        if (user !== undefined && pass !== undefined){
            login(user,pass);
        }
    }
}
function login(useremail, userpassword) {
    var url = "servlets/DataManager?action=login&useremail=" + escape(useremail) + "&userpass=" + escape(userpassword);
    var xml = getXML(url);
    var status = false;
    crombUser = null;
    if (xml !== null) {
        var nodes = xml.getElementsByTagName("status");
        for (var i = 0; i < nodes.length; i++) {
            var content = nodes[i].childNodes[0].nodeValue;
            if (content === "SUCCESS") {
                status = true;
                var userNode = xml.getElementsByTagName("user");
                crombUser = new User();
                for (var j = 0; j < userNode.length; j++) {
                    crombUser.username = userNode[j].getAttribute("name");
                    crombUser.email = userNode[j].getAttribute("email");
                }
                break;
            } else {
                crombUser = null;
            }
        }
    }
    return status;
}
function isLogged() {
    var islogged = false;
    if (crombUser === null) {
        var url = "servlets/DataManager?action=islogged";
        var xml = getXML(url);
        if (xml !== null) {
            var nodes = xml.getElementsByTagName("status");
            for (var i = 0; i < nodes.length; i++) {
                var status = nodes[i].childNodes[0].nodeValue;
                if (status === "SUCCESS") {
                    islogged = true;
                    if (crombUser === null) {
                        var userNode = xml.getElementsByTagName("user");
                        crombUser = new User();
                        for (var j = 0; j < userNode.length; j++) {
                            crombUser.username = userNode[j].getAttribute("name");
                            crombUser.email = userNode[j].getAttribute("email");
                        }
                    }
                    break;
                }
            }
        }
    } else {
        islogged = true;
    }
    return islogged;
}
//Crombs Related End

function getXML(url) {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var xml = null;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            var parser = new DOMParser();
            xml = parser.parseFromString(xmlhttp.responseText.trim(), "text/xml");
        }
    };
    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "text/xml");
    xmlhttp.overrideMimeType('text/xml');
    xmlhttp.send();
    return xml;
}

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
    return replateTagWithFunction(text.replace(exp, "<a href='$1' target='_blank'>$1</a>"));
}
function replateTagWithFunction(text) {
    var exp = /#([a-z0-9-]+;|[a-z0-9-]+)/ig;
    return text.replace(exp, "<div onclick=showWalletTags('#$1'); class='tag'>#$1</div>");
}
function renderDatetime(stringDT) {
    try{
        return new Date(stringDT.replace(" ", "T") + "-05:00").toLocaleString();
    } catch(err){
        return stringDT;
    }
    //return stringDT.replace(" ", "T")+"-0500";
}
function renderDate(stringDT) {
    try{
      return new Date(stringDT.replace(" ", "T") + "-05:00").toLocaleDateString();
    }catch(err){
      return stringDT;   
    }
    //return stringDT.replace(" ", "T")+"-0500";
}
function renderDistance(distance) {
    if (distance === undefined) {
        return "NA";
    }
    if (distance >= 1000) {
        return Math.round(distance / 100) / 10 + "km";
    } else {
        return Math.round(distance * 10) / 10 + "m";
    }
}
function setCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name)
{
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start === -1)
    {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start === -1)
    {
        c_value = null;
    }
    else
    {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end === -1)
        {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}
